package com.me.mysqladmin.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.me.mysqladmin.service.DataBaseService;

/**
 * 连接状态拦截器
 * @author dong
 */
@Controller
public class ConnectInterceptor implements HandlerInterceptor {
	// 日志记录器
	private final static Logger LOG = LoggerFactory.getLogger(ConnectInterceptor.class);
	
	// 注入业务组件
	@Resource
	private DataBaseService dataBaseService;
	
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 判断数据库连接状态
		boolean flag = dataBaseService.testConnection();
		HttpSession session = request.getSession();
		if(!flag){
			// 清空位置信息
			session.setAttribute("serverName", "");
			session.setAttribute("databaseName", "");
			session.setAttribute("tableName", "");
		} else{
			// 取得当前位置
			String serverName = request.getParameter("serverName");
			String databaseName = request.getParameter("databaseName");
			String tableName = request.getParameter("tableName");
			if(serverName == null || "".equals(serverName)){
				serverName = request.getServerName();
			}
			// 设置session
			session.setAttribute("serverName", serverName);
			session.setAttribute("databaseName", databaseName);
			session.setAttribute("tableName", tableName);
			// 打印位置信息
			LOG.info("---------serverName:" + serverName + "---------");
			LOG.info("---------databaseName:" + databaseName + "---------");
			LOG.info("---------tableName:" + tableName + "---------");
		}
		return true;
	}
}
